<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi as UserApi;
use Think\Model;

/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class WarehouseController extends AdminController {

    /**
     * 后台首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
        if(UID){
            $this->meta_title = '管理首页';
            $this->display();
        } else {
            $this->redirect('Public/login');
        }
    }
    
    /**
     * 入库商品列表
     * @author James
     * 2016-01-15
     */
    public function inlist() {
        
        $Model = new Model();
        
        $pname = I('pname');
        
        if($pname){
            $where = " and pname like '%".$pname."%' ";
        }
        
        $batchNo = I('batchNo');
        
        if($batchNo){
            $where = " and batchNo like '%".$batchNo."%' ";
        }
        
        $sql = "select batchNo from gr_storage_in a where status = 1 ".$where." group by batchNo";
        $list1 = $Model->query($sql);

        //************************************************

        $total = count($list1);
        
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }

        $page = new \Think\Page($total, $listRows, $REQUEST);
        
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        
        $sql = "select wid,batchNo,count(1) cnt,min(createdAt) createdAt,max(updateAt) updateAt,max(updateUser) updateUser 
            from gr_storage_in a 
            where status = 1 ".$where."
            group by wid,batchNo ORDER BY batchNo desc limit ".$page->firstRow . ',' . $page->listRows;
        $list = $Model->query($sql);
        
        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display('inlist');
    }
    
    /**
     * 出库商品列表
     * @author James
     * 2016-01-15
     */
    public function outlist() {
        
        $Model = new Model();
        
        $batchNo = I('batchNo');
        
        if($batchNo){
            $where = " and batchNo like '%".$batchNo."%' ";
        }
        
        $sql = "select batchNo from gr_storage_out a where status = 1 ".$where." group by batchNo";
        $list1 = $Model->query($sql);

        //************************************************

        $total = count($list1);
        
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }

        $page = new \Think\Page($total, $listRows, $REQUEST);
        
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        
        $sql = "select wid,batchNo,count(1) cnt,min(createdAt) createdAt,max(updateAt) updateAt,max(updateUser) updateUser 
            from gr_storage_out a 
            where status = 1 ".$where."
            group by wid,batchNo ORDER BY batchNo desc limit ".$page->firstRow . ',' . $page->listRows;
        $list = $Model->query($sql);
        
        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display('outlist');
    }
    
    /**
     * 入库商品列表
     * @author James
     * 2016-01-15
     */
    public function indetail() {
        
        $pname = I('pname');
        if($pname){
            $map['pname'] = array('like', '%' . (string) $pname . '%');
        }
        
        $batchNo = I('batchNo');
        if($batchNo){
            $map['batchNo'] = array('like', '%' . (string) $batchNo . '%');
        }

        $map['status']  =   1;
        
        $list = $this->lists('storage_in', $map,'updateAt desc');
        int_to_string($list);
        
        $this->assign('_list', $list);
        $this->assign('_uid', UID);
        $this->meta_title = '数据列表';
        $this->display();
    }
    
    /**
     * 出库商品列表
     * @author James
     * 2016-01-15
     */
    public function outdetail() {
        
        $pname = I('pname');
        if($pname){
            $map['pname'] = array('like', '%' . (string) $pname . '%');
        }
        
        $batchNo = I('batchNo');
        if($batchNo){
            $map['batchNo'] = array('like', '%' . (string) $batchNo . '%');
        }

        $map['status']  =   1;
        
        $list = $this->lists('storage_out', $map,'updateAt desc');
        int_to_string($list);
        
        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display();
    }
    
    /**
     * 入库
     * @author James
     * 2016-01-14
     */
    public function inadd(){
        if(IS_POST){
            $batchNo = I('batchNo');
            $wid = I('wid');
            $spec_array = I('spec');
            $cnt_array = I('cnt');
            $id_array = I('id');
            $type_array = I('type');
            
            for ($i = 0; $i < count($id_array); $i++) {
                if ($id_array[$i] == ""  || $spec_array[$i] == "" || $cnt_array[$i] == "") {
                    $this->error("入库商品信息不能为空");
                }
            }
            
            for ($i = 0; $i < count($id_array); $i++) {
                
                $Product = M("Product"); // 实例化Product对象
                $map2['id'] = $id_array[$i];
                $info = $Product->where($map2)->find();
                
                $dataList[] = array('batchNo' => $batchNo, 
                    'wid' => $wid,
                    'pid' => $id_array[$i], 
                    'spu' => $info['spu'], 
                    'pname' => $info['name'], 
                    'spec' => $spec_array[$i],
                    'cnt' => $cnt_array[$i],
                    'type' => $type_array[$i],
                    'status' => 1,
                    'createdAt' => NOW_TIME,
                    'updateAt' => NOW_TIME,
                    'createdUser' => UID,
                    'updateUser' => UID);
                
                $Inventory = M("Inventory"); // 实例化Inventory对象
                
                //判断该商品是否存在实时库存表（gr_inventory）内
                $id = $Inventory->where(array('pid'=>$id_array[$i],'spec'=>$spec_array[$i],'type'=>$type_array[$i]))->getField('id');
                
                if($id){
                    //入库时，如果该商品在实时库存表（gr_inventory）内，则在实时库存表（gr_inventory）内更新该商品的实时库存
                    $Inventory->where(array('id'=>$id))->setInc('cnt',$cnt_array[$i]);
                    
                    $data = array('updateUser'=>UID,'updateAt'=>NOW_TIME);
                    $Inventory-> where(array('id'=>$id))->setField($data);
                }else{
                    //入库时，如果该商品不在实时库存表（gr_inventory）内，则往实时库存表（gr_inventory）内新增该商品
                    $data['pid'] = $id_array[$i];
                    $data['spu'] = $info['spu'];
                    $data['pname'] = $info['name'];
                    $data['classname'] = $info['classname'];
                    $data['spec'] = $spec_array[$i];
                    $data['cnt'] = $cnt_array[$i];
                    $data['type'] = $type_array[$i];
                    $data['status'] = 1;
                    $data['createdAt'] = NOW_TIME;
                    $data['updateAt'] = NOW_TIME;
                    $data['createdUser'] = UID;
                    $data['updateUser'] = UID;
                    $Inventory->add($data);
                }
            }
            D('storage_in')->addAll($dataList);
            
            $this->success('入库成功！', U('inlist'));
        }else{
            $batchNo = I('batchNo');
            $wid = I('wid');
            
            if(!$batchNo && !$wid){
                $batchNo = date("Ymdhis",time());
                $this->assign( '_batchNo', $batchNo );
            }
            
            $map['status']  =   1;
            $wlist = $this->lists('Warehouse', $map,'createdAt asc');
            
            $prolist = M("Product")->where('status=1')->order('createdAt')->select();
            
            $this->assign( 'product', json_encode($prolist) );
            $this->assign( '_wlist', $wlist );
            $this->assign( '_wid', $wid );
            
            $this->meta_title = '入库管理';
            
            if($wid){
                
                $map['batchNo'] = array('like', '%' . (string) $batchNo . '%');
                $list = $this->lists('storage_in', $map,'updateAt desc');
                
                int_to_string($list);
                $this->assign('_list', $list);
                $this->assign('_uid', UID);
                $this->display('indetail');
            }else{
                $this->display('inadd');
            }
        }
    }
    
    /**
     * 出库
     * @author James
     * 2016-01-14
     */
    public function outadd(){
        if(IS_POST){
            $batchNo = I('batchNo');
            $wid = I('wid');
            $id_array = I('id');
            $cnt_array = I('cnt');
            for ($i = 0; $i < count($id_array); $i++) {
                if ($id_array[$i] == "" || $cnt_array[$i] == "") {
                    $this->error("出库信息不能为空");
                }
            }
            for ($i = 0; $i < count($id_array); $i++) {
                $Inventory = M("Inventory"); // 实例化Inventory对象
                $map2['id'] = $id_array[$i];
                $info = $Inventory->where($map2)->find();
                $dataList[] = array(
                    'batchNo' => $batchNo,
                    'wid' => $wid,
                    'pid' => $info['pid'],
                    'spec' => $info['spec'],
                    'pname' => $info['pname'],
                    'cnt' => $cnt_array[$i],
                    'createdAt' => NOW_TIME,
                    'updateAt' => NOW_TIME,
                    'createdUser' => UID,
                    'updateUser' => UID
                );
                $Inventory->where($map2)->setDec('cnt',$cnt_array[$i]);
                $data = array('updateUser'=>UID,'updateAt'=>NOW_TIME);
                $Inventory-> where($map2)->setField($data);
            }
            D('storage_out')->addAll($dataList);
            $this->success("操作成功");
        }else{
            
            $batchNo = I('batchNo');
            $wid = I('wid');
            
            if(!$batchNo && !$wid){
                $batchNo = date("Ymdhis",time());
                $this->assign( '_batchNo', $batchNo );
            }
            
            $map['status']  =   1;
            $wlist = $this->lists('Warehouse', $map,'createdAt asc');
            $prolist = M("Inventory")->where('status=1')->order('createdAt')->select();
            
            $this->assign( 'product', json_encode($prolist) );
            $this->assign( '_wlist', $wlist );
            $this->assign( '_wid', $wid );
            
            $this->meta_title = '出库管理';
            
            if($wid){
                
                $map['batchNo'] = array('like', '%' . (string) $batchNo . '%');
                $list = $this->lists('storage_out', $map,'updateAt desc');
                
                int_to_string($list);
                $this->assign('_list', $list);
                $this->display('outdetail');
            }else{
                $this->display('outadd');
            }
            
            $this->assign( '_prolist', $prolist );
            $this->assign( '_batchNo', $batchNo );
        }
    }
    
    /**
     * 删除入库数据
     * @author James
     * 2016-02-26
     */
    public function indel($id = 0) {
        if ($id) {
            $Storage = M("storage_in");
            $data = array('status'=>-1,'updateAt' => NOW_TIME, 'updateUser' => UID);
            $result = $Storage-> where(array('id'=>$id))->setField($data);
            
            if($result){
                //获取要删除的入库数量
                $cnt = $Storage->where(array('id'=>$id))->getField('cnt');
                $pid = $Storage->where(array('id'=>$id))->getField('pid');
                $spec = $Storage->where(array('id'=>$id))->getField('spec');
                $type = $Storage->where(array('id'=>$id))->getField('type');
                
                //更新实时库存表　库存减　几
                $Inventory = M("Inventory"); // 实例化Inventory对象
                $iid = $Inventory->where(array('pid'=>$pid,'spec'=>$spec,'type'=>$type))->getField('id');
                $Inventory->where(array('id'=>$iid))->setDec('cnt',$cnt);
                
                $this->success('删除成功！', U('inlist'));
            }else{
                $this->error("删除失败！");
            }
        }
    }
    
    /**
     * 实时库存列表
     */
    public function inventorylist(){
        $map['status']=1;
        $classname = I('classname');
        if($classname){
            $map['classname'] = array('like', '%' . (string) $classname . '%');
        }
        
        $title = I('title');
        
        if($title){
            $map['pname'] = array('like', '%' . (string) $title . '%');
        }
        
        $type = I('type');
        
        if($type){
            $map['type'] = $type;
        }
        
        $list = $this->lists('inventory', $map,'classname asc,pname asc');
        int_to_string($list);

        $this->assign('_list', $list);
        
        $classList = M("classify")->where(array('status'=>1))->select();
        $data['classList'] = $classList;
        $this->data = $data;
        
        $this->assign('_type', $type);
        $this->assign('_classname', $classname);
        
        $this->meta_title = '数据列表';
        $this->display();
    }

    /**
     * 盘点记录
     */
    public function checkinfolist(){
        $map['status']=1;
        
        $list = $this->lists('checkinfo', $map,'createdAt desc');
        int_to_string($list);

        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display();
    }
    
    /**
     * 盘点详细列表
     */
    public function checkflowlist(){
        $uid = $_REQUEST['uid'];
        $createdAt = $_REQUEST['createdAt'];
        
        $map['status']=1;
        $title = I('title');
        if($title){
            $map['pname'] = array('like', '%' . (string) $title . '%');
        }
        if($uid){
            $map['createdUser'] = $uid;
        }
        if($createdAt){
            $map['createdAt'] = $createdAt;
        }
        $list = $this->lists('checkflow', $map,'createdAt desc');
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display();
    }

    /**
     * 盘点
     */
    public function checkflow(){
        if(IS_POST){
            $now = NOW_TIME;
            
            $inventoryid_array = I('inventoryid');
            $cnt_array = I('aftercnt');
            
            for ($i = 0; $i < count($inventoryid_array); $i++) {
                if ($inventoryid_array[$i] == ""  || $cnt_array[$i] == "") {
                    $this->error("盘点信息不能为空");
                }
            }
            
            for ($i = 0; $i < count($inventoryid_array); $i++) {
                $dataList[] = array( 
                    'pid' => explode(',',$inventoryid_array[$i])[1], 
                    'pname' => explode(',',$inventoryid_array[$i])[2], 
                    'spec' => explode(',',$inventoryid_array[$i])[3], 
                    'after' => $cnt_array[$i], 
                    'before' => explode(',',$inventoryid_array[$i])[4], 
                    'spu' => explode(',',$inventoryid_array[$i])[5], 
                    'createdAt' => $now,
                    'updateAt' => $now,
                    'createdUser' => UID,
                    'updateUser' => UID);
                
                $inventory = M("inventory"); 
                $id = explode(',',$inventoryid_array[$i])[0];
                $data = array('updateUser'=>UID,'updateAt'=>$now,'cnt'=>$cnt_array[$i]);
                $inventory-> where(array('id'=>$id))->setField($data);
            }
            D('checkflow')->addAll($dataList);
            M('checkinfo')->add(array('createdAt'=>$now,'createdUser'=>UID));
            $this->redirect("Warehouse/checkinfolist");
        }else{
            $sql = "select a.* from gr_inventory a where a.status = 1 order by createdAt asc";
            $model = new \Think\Model();
            $list = $model->query($sql);
            int_to_string($list);

            $this->assign('_prolist', $list);
            $this->meta_title = '数据列表';
            $this->display();
        }
    }

    //仓库管理
    public function warehouse(){
        $name       =   I('name');
        $map['status']  =   array('egt',0);
        if(is_numeric($name)){
            $map['name']=   array(intval($name),array('like','%'.$name.'%'),'_multi'=>true);
        }else{
            $map['name']    =   array('like', '%'.(string)$name.'%');
        }
        $this->meta_title = '仓库信息';
        $Warehouse = M('warehouse') ;

        $warehouse = $Warehouse->where($map);
        $list = $this->lists($warehouse);
        $list = int_to_string($list);

        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $this->assign('_list',$list);
        $this->display();
    }
    public function createWarehouse(){
        if ( empty($this->warehouse) ) {
            $this->assign('warehouse',array('name'=>null,'id'=>null,'shi'=>null));//排除notice信息
        }
        $this->meta_title = '新增仓库';
        $this->display('editwarehouse');
    }

    public function editWarehouse(){
        $warehouse = M('warehouse')->find( (int)$_GET['id'] );
        $this->assign('warehouse',$warehouse);
        $this->meta_title = '编辑仓库';
        $this->display();
    }
    public function writeWarehouse(){
        $product = M('warehouse');
        $data = $product->create();
        if($data){
            if(empty($data['id'])){
                $data['createdAt'] = NOW_TIME ;
                $data['createdUser'] = UID ;
                $data['updatedAt'] = NOW_TIME ;
                $data['updatedUser'] = UID ;
                $r = $product->add($data);
            }else{
                $data['updatedAt'] = NOW_TIME ;
                $data['updatedUser'] = UID ;
                $r = $product->save($data);
            }
            if($r===false){
                $this->error('操作失败'.$product->getError());
            } else{
                $this->success('操作成功!',U('warehouse'));
            }
        }else{
            $this->error('操作失败'.$product->getError());
        }
    }
    public function changeStatus($method=null){
        if ( empty($_REQUEST['id']) ) {
            $this->error('请选择要操作的数据!');
        }
        switch ( strtolower($method) ){
            case 'forbid':
                $this->forbid('warehouse');
                break;
            case 'resume':
                $this->resume('warehouse');
                break;
            case 'delete':
                $this->delete('warehouse');
                break;
            default:
                $this->error($method.'参数非法');
        }
    }

    /**
     * 实时库存导出
     * @author James
     * 2016-02-18
     */
    public function kcExport() {
        if (!IS_POST){
            $this->redirect("Warehouse/inventorylist");
        }
        
        $classname = I('classname');
        if($classname){
            $where .= " and classname like '%".$classname."%' ";
        }
        
        $type = I('type');
        if($type){
            $where .= " and type like '%".$type."%' ";
        }
        
        $title = I('title');
        
        if($title){
            $where .= " and pname like '%".$title."%' ";
        }
        
        $sql = "select a.classname,a.spu,a.pname,a.spec,a.cnt,CASE WHEN a.type = 1 THEN '原包装' WHEN a.type = 2 THEN '成品' END TYPE,"
                . "FROM_UNIXTIME(a.updateAt) updateAt,"
                . "CASE WHEN a.status = 1 THEN '正常' WHEN a.status = 0 THEN '禁用' WHEN a.status = -1 THEN '删除' END STATUS "
                . "from gr_inventory a where 1=1 ".$where." "
                . "ORDER BY classname ASC,pname ASC";
        
        $Model = new Model();
        $data = $Model->query($sql);
        if ($data) {
            $orderTable = M('order');
            $data1 = array('isExport' => 1);

            $args = array_map(function($src){
                                return $src['orderid'];}, $data);
            $map['orderid']  = array('in',$args);
            $result = $orderTable->where($map)->setField($data1);
            
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";
            
            $headArr = array("商品分类","商品编号", "商品名称", "规格", "	库存数量","商品类型","盘点时间", "状态");
            
            $title = "实时库存列表";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
    
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);


        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $key += 1;
        }

        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $objActSheet->getColumnDimension('a')->setWidth(20);
                $objActSheet->getColumnDimension('b')->setWidth(20);
                if (count($headArr) == 12){
                    $objActSheet->getColumnDimension('d')->setWidth(20);
                    $objActSheet->getColumnDimension('h')->setWidth(20);
                    $objActSheet->getColumnDimension('i')->setWidth(20);
                    $objActSheet->getColumnDimension('j')->setWidth(30);
                    $objActSheet->getColumnDimension('l')->setWidth(100);
                }else{
                    $objActSheet->getColumnDimension('g')->setWidth(20);
                    $objActSheet->getColumnDimension('h')->setWidth(20);
                    $objActSheet->getColumnDimension('i')->setWidth(30);
                    $objActSheet->getColumnDimension('j')->setWidth(30);
                    $objActSheet->getColumnDimension('k')->setWidth(100);
                }
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
}
